<?php
namespace app\controllers\admin\uni\data;

use app\controllers\admin\uni\order\BaseController;
use app\models\order\Order;
use app\models\pay\Pay;
use app\models\product\Product;
use app\models\user\User;
use yii\helpers\ArrayHelper;

class IndexController extends BaseController
{
    public function actionDay()
    {
        $product = Product::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->count();
        $member = User::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->count();
        $finance = Pay::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->andWhere(['status' => 1])
            ->sum('amount');
        $order = Order::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->count();

        return $this->success([
            'product' => (int)$product,
            'member' => (int)$member,
            'finance' => (float)$finance,
            'order' => (int)$order
        ]);
    }

    public function actionMonth()
    {
        // 有错误
        // $order = Order::find()
        //     ->select(['count(1) as count', 'DATE_FORMAT(create_time, "%Y-%m-%d") as dt'])
        //     // ->where(['<=', 'DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH)', 'date(create_time)'])
        //     ->where('DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) <= date(create_time)')
        //     ->groupBy('dt')
        //     ->orderBy(['dt' => SORT_ASC])
        //     ->asArray()
        //     ->all();

        $limit = $this->post('count', 30);

        // 这里取最近30天, 然后再倒序出来
        $order = Order::find()
            ->select(['count(1) as count', 'DATE_FORMAT(create_time, "%Y-%m-%d") as dt'])
            ->groupBy('dt')
            ->orderBy(['dt' => SORT_DESC])
            ->limit($limit)
            ->asArray()
            ->all();
        $order = array_reverse($order);

        $member = User::find()
            ->select(['count(1) as count', 'DATE_FORMAT(create_time, "%Y-%m-%d") as dt'])
            ->groupBy('dt')
            ->orderBy(['dt' => SORT_DESC])
            ->limit($limit)
            ->asArray()
            ->all();
        $member = array_reverse($member);

        return $this->success(['order' => $order, 'member' => $member]);
    }

    public function actionWeek()
    {

    }
}